import 'dart:async';
import "package:ct_pa_majordomo/config/theme_vars.dart";
import "package:ct_pa_majordomo/pages/widgets/menu_block.dart";
import "package:ct_pa_majordomo/utils/event_bus.dart";
import "package:flutter/cupertino.dart";
import "package:flutter/material.dart";

class Base extends StatefulWidget {
  final Map? info;
  const Base({super.key, this.info});

  @override
  State<Base> createState() => _BaseState();
}

class _BaseState extends State<Base> {
  Map _meterInfo = {};
  late StreamSubscription _subscription;
  
  @override
  void initState() {
    super.initState();
    _updateMeterInfo();
    
    // 订阅电表事件
    _subscription = eventBus.on.listen((event) {
      if (event is ElectricityMeterEvent) {
        _handleElectricityMeterEvent(event);
      }
    });
  }
  
  @override
  void dispose() {
    // 取消订阅
    _subscription.cancel();
    super.dispose();
  }
  
  void _updateMeterInfo() {
    // 获取路由传递的参数，如果没有直接传入info，则从路由参数中获取
    final Map info = widget.info ?? (ModalRoute.of(context)?.settings.arguments as Map? ?? {});
    setState(() {
      _meterInfo = Map.from(info);
    });
  }
  
  // 处理电表名称更新事件
  void _handleElectricityMeterEvent(ElectricityMeterEvent event) {
    if (event.type == 'nameChanged') {
      // 如果是当前电表的名称更新事件
      if (event.data["electricityMeterId"] == _meterInfo["electricityMeterId"]) {
        setState(() {
          _meterInfo["name"] = event.data["name"];
        });
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        iconTheme: const IconThemeData(color: Colors.white),
        title: const Text("基本信息", style: TextStyle(color: Colors.white),),
        centerTitle: true,
        backgroundColor: ThemeVars.colorPrimary,
        leading: IconButton(
          icon: const Icon(Icons.arrow_back_ios_new),
          onPressed: () {
            Navigator.pop(context);
          },
        ),
      ),
      body: ListView(
        children: [
          Column(
            children: [
              MenuBlock(
                borderRadius: BorderRadius.circular(0),
                items: [
                  MenuBlockItem(
                    text: "名称",
                    showArrow: false,
                    suffix: Text(_meterInfo["name"] ?? "-"),
                  ),
                  MenuBlockItem(
                    text: "电表号",
                    showArrow: false,
                    suffix: Text(_meterInfo["number"] ?? "-"),
                  ),
                  // MenuBlockItem(
                  //   text: "状态",
                  //   showArrow: false,
                  //   suffix: Text(_meterInfo["status"] == "2" ? "已开户" : "未开户"),
                  // ),
                  MenuBlockItem(
                    text: "剩余金额",
                    showArrow: false,
                    suffix: Text("${_meterInfo["remainAmount"] ?? "0"}元"),
                  ),
                  MenuBlockItem(
                    text: "当前度数",
                    showArrow: false,
                    suffix: Text("${_meterInfo["reminderKwh"] ?? "-"}"),
                  ),
                  MenuBlockItem(
                    text: "总度数",
                    showArrow: false,
                    suffix: Text("${_meterInfo["totalKwh"] ?? "-"}"),
                  ),
                ],
              ),
              const SizedBox(height: 10,),
              Text("更新时间：${_meterInfo['updateTime'] ?? '-'}", textAlign: TextAlign.center, style: const TextStyle(color: ThemeVars.colorTextTer),),
            ],
          )
        ],
      ),
    );
  }

}